/*
 * @(#)HapiMllpStartupListener.java
 * Date 2013-03-30
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.hapiservice;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.lang3.math.NumberUtils;


/**
 *
 * @author jim
 */
public class HapiMllpStartupListener implements ServletContextListener {

    /** Field description */
    public static final String MLLP_SERVICE = "MllpService";

    /** Field description */
    private static final String HAPI_PORT = "mllpPort";

    /** Field description */
    private HapiMllpService mllpService;

    /**
     * Method description
     *
     *
     * @param sce
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {

        if (this.mllpService != null) {
            
            this.mllpService.shutdown();
        }
    }

    /**
     * Method description
     *
     *
     * @param sce
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {

        ServletContext sc = sce.getServletContext();

        String portstr = sc.getInitParameter(HAPI_PORT);

        try {

            int port = NumberUtils.toInt(portstr, -1);

            this.mllpService = new HapiMllpService(port);
            this.mllpService.start();

        } catch (InterruptedException e) {

            throw new IllegalStateException(e);
        }

        sc.setAttribute(MLLP_SERVICE, this.mllpService);
    }
}
